package cgl.narada.service.security.kmc.messages;

import java.io.IOException;
import java.io.Serializable;

import org.apache.log4j.Logger;

import cgl.narada.util.ObjectMarshaller;

/**
 * Encapsulates various messages sent to the KMC <br>
 * Created on Sep 8, 2005
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */
public class KMCMessage implements Serializable {

    static Logger log = Logger.getLogger("KMCMessage");

    /** The payload is asecure key creation request. To be used by Topic owner */
    public static final int KmcMSG_SECURE_TOPIC_KEY_CREATE_MODIFY = 1;

    /**
     * The payload is secure topic key request. To be used by one of authorized
     * publisher/ subscriber
     */
    public static final int KmcMSG_SECURE_TOPIC_KEY_REQUEST = 2;

    private int messageType;

    private byte[] payload;

    public KMCMessage(int type, byte[] data) {
        messageType = type;
        payload = data;
    }

    /**
     * Marshalls the object into an array of bytes.
     * 
     * @return an array of bytes representing the marshaller object, null if
     *         error occurs
     */
    public byte[] getBytes() {
        try {
            return ObjectMarshaller.marshall(this);
        } catch (IOException e) {
            log.error("", e);
            return null;
        }
    }

    /**
     * Unmarshalls the bytes as a KMCMessage object
     * 
     * @param objectBytes
     * @return KMCMessage if successful, null if error occurs
     */
    public static KMCMessage createObjectFromBytes(byte[] objectBytes) {
        try {
            return (KMCMessage) ObjectMarshaller.unmarshall(objectBytes);
        } catch (IOException e) {
            log.error("", e);
        } catch (ClassNotFoundException e) {
            log.error("", e);
        }
        return null;
    }

    /**
     * @return Returns the messageType.
     */
    public int getMessageType() {
        return messageType;
    }

    /**
     * @return Returns the payload.
     */
    public byte[] getPayload() {
        return payload;
    }
}
